<template>
  <div class="edit">
    <van-nav-bar
      title="编辑资料"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image fit="cover" round :src="userInfo.photo" />
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 信息展示 -->
    <van-cell-group>
      <van-cell
        is-link
        title="名称"
        :value="userInfo.name"
        @click="nameClick"
      />
      <van-cell
        is-link
        @click="genderClick"
        title="性别"
        :value="userInfo.gender ? '女' : '男'"
      >
      </van-cell>
      <van-cell
        is-link
        title="生日"
        :value="userInfo.birthday"
        @click="datePickerClick"
      />
    </van-cell-group>

    <!-- 名称弹窗 -->
    <van-dialog
      v-model="showDialog"
      title="修改名称"
      @confirm="getNameClick"
      show-cancel-button
    >
      <van-field v-model="newName" ref="nameFilse" :placeholder="newName" />
    </van-dialog>

    <!-- 性别弹窗 -->
    <van-popup
      v-model="showGender"
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-nav-bar
        title="修改性别"
        left-arrow
        @click-left="showGender = false"
      />
      <van-cell title="男" is-link @click="getGenderClick(0)" />
      <van-cell title="女" is-link @click="getGenderClick(1)" />
    </van-popup>

    <!-- DatetimePicker 时间选择 -->
    <van-popup
      v-model="showDatePick"
      position="bottom"
      :style="{ height: '30%' }"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="updateBirthday"
        @cancel="showDatePick = false"
      />
    </van-popup>
    <div class="cropper-box" v-show="showCropper">
      <vueCropper
        ref="cropper"
        :img="img"
        autoCropWidth="120"
        autoCropHeight="120"
        fixed
        autoCrop
      ></vueCropper>
      <van-button type="info" class="confirm-btn" @click="submitPhoto"
        >确定</van-button
      >
      <van-button type="primary" class="cancel-btn" @click="showCropper = false"
        >取消</van-button
      >
    </div>
  </div>
</template>

<script>
//导入mapState辅助函数
import { mapState } from 'vuex'
//导入请求接口
import { editUserInfo, editUserFile } from './user'
//导入时间管理插件
import moment from 'moment'
moment.locale('zh-cn')

//组件内使用
import { VueCropper } from 'vue-cropper'

export default {
  name: 'edit',
  data () {
    return {
      showDialog: false, //名称弹窗
      newName: '', //输入的姓名
      showGender: false, //性别弹窗
      showDatePick: false, //生日弹窗
      minDate: new Date(1937, 1, 1),
      maxDate: new Date(2049, 10, 1),
      currentDate: new Date(), //当前选中的时期
      img: '', //要裁切的图片
      showCropper: false //裁切的窗口
    }
  },
  //计算属性解决代码重复问题
  computed: {
    //等同于下面aaa
    ...mapState(['userInfo'])
    // aaa(){
    //   return this.$store.state.aaa
    // }

    //用上面简便
    // 原生用this.$store.state.aaa获取在state中数据
  },
  methods: {
    //点击名称单元格
    nameClick () {
      this.showDialog = true
      this.newName = this.userInfo.name
      //使用高级定时器解决focus的显示问题
      this.$nextTick(function () {
        this.$refs.nameFilse.focus()
      })
    },
    //修改名字保存到state
    getNameClick () {
      editUserInfo({ name: this.newName }).then(res => {
        // console.log(res)
        this.$toast.success('更新成功!')

        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          name: this.newName
        })
      })
    },
    //点击性别
    genderClick () {
      this.showGender = true
    },
    //修改性别
    getGenderClick (gender) {
      editUserInfo({ gender }).then(res => {
        this.$toast.success('更新成功!')

        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          gender: gender
        })
        this.showGender = false
      })
    },
    //点击生日弹窗
    datePickerClick () {
      this.showDatePick = true

      //把vuex中的字符串生成date对象
      let date = new Date(this.userInfo.birthday)

      //把日期对象给到currentDate
      this.currentDate = date
    },
    //修改生日
    updateBirthday () {
      let birthday = moment(this.currentDate).format('YYYY-MM-DD')
      editUserInfo({ birthday }).then(res => {
        this.$toast.success('更新成功!')
        //(2)更新vuex数据
        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          birthday: birthday
        })
        this.showGender = false
      })
    },
    //修改头像
    afterRead (file) {
      // 此时可以自行将文件上传至服务器
      //console.log(file)
      this.img = file.content

      this.showCropper = true
    },
    submitPhoto () {
      // 获取截图的blob数据
      this.$refs.cropper.getCropBlob(data => {
        // console.log(data)

        // 获取Blob这种格式
        // formData + 接口提交到远程
        //使用formdata处理文件数据
        let fd = new FormData()
        fd.append('photo', data)
        editUserFile(fd).then(res => {
          this.$toast({
            type: 'success', // success 成功, loading 加载, fail 失败
            message: '修改成功'
          })
          this.$store.commit('setUserInfo', {
            ...this.userInfo,
            photo: res.data.data.photo
          })

          this.showCropper = false
        })
      })
    }
  },
  components: {
    VueCropper
  }
}
</script>

<style lang="less">
.edit {
  // 导航条部分
  .van-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
  }
  // 头像部分
  .avatar {
    padding: 20px 0;
    text-align: center;
    .van-image {
      width: 120px;
      height: 120px;
    }
  }
  //文件上传
  .van-uploader {
    position: absolute;
    opacity: 0;
    left: 50%;
    transform: translateX(-50%); //往左走自身一半
    width: 120px;
    height: 120px;
    .van-uploader__upload {
      width: 120px;
      height: 120px;
    }
  }
}
// 裁切弹框样式
.cropper-box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  .confirm-btn {
    position: absolute;
    bottom: 0;
    right: 0;
  }
  .cancel-btn {
    position: absolute;
    left: 0;
    bottom: 0;
  }
}
</style>
